package com.wenge.datagroup.storage.dataprocess;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author：WeiPengCheng
 * @Date：2022-07-27 9:58
 *         desc:多语种机器翻译
 **/
public class MultilingualTranslation {
    private static Logger logger = LoggerFactory.getLogger(MultilingualTranslation.class);

    public String translationUrl;

    public MultilingualTranslation(String translationUrl) {
        this.translationUrl = translationUrl;
    }

    /**
     * 多语种机器翻译
     *
     * @param par:待翻译文本
     * @param src_lang:源语种
     */
    public String analysis(String par, String src_lang) {

        long start = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("input_text", par);
        jsonObject.put("src_lang", src_lang);
        jsonObject.put("tgt_lang", "zh");

        OkHttpClient httpClient = new OkHttpClient()
                .newBuilder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .build();

        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("content", jsonObject.toJSONString()).
                        addFormDataPart("id", "1")
                .build();
        Request request = new Request.Builder()
                .url(translationUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        try {
            Response response = httpClient.newCall(request).execute();
            if (response.code() == 200) {
                String data = response.body().string();
                logger.info("多语种翻译请求成功!!" + data);
                if (JSON.parseObject(data).getString("code").equals("200")) {
                    String string = JSON.parseObject(data).getJSONObject("data").getString("tgt");
                    logger.info("翻译参数:"+jsonObject);
                    logger.info("翻译结果:" + string);
                    return string;
                }
            } else {
                logger.info("多语种翻译接口请求异常! code:{}", response.code());
            }
        } catch (IOException e) {
            logger.error("多语种翻译接口请求异常!");
            e.printStackTrace();
        } finally {
            logger.info("多语言翻译接口处理耗时： " + (System.currentTimeMillis() - start) + " ms");
        }

        return null;
    }
}
